<template>
  <div>
    <div>
      <!-- {{ modelValue }} {{ placeholder }} -->
    </div>
    <a-select
      v-model:value="value2"
      mode="multiple"
      label-in-value
      :default-active-first-option="false"
      :filter-option="false"
      :options="selectOptions"
      :placeholder="placeholder"
      style="width: 90%"
      @search="handleSearch"
      @dropdownVisibleChange="dropdownVisibleChange"
      @change="handleChange"
    >
      <template #dropdownRender="{ menuNode: menu }">
        <v-nodes :vnodes="menu" />
        <template v-if="options.length > 7">
          <a-divider style="margin: 4px 0" />
          <div
            style="padding: 4px 8px; cursor: pointer"
            @mousedown="e => e.preventDefault()"
            @click="searchMore"
          >
            <search-outlined />
            搜索更多
          </div>
        </template>
      </template>
    </a-select>
  </div>
</template>

<script setup>
function VNodes(_, { attrs }) {
  return attrs.vnodes
}

import { computed } from 'vue'

const props = defineProps(['modelValue', 'options', 'placeholder'])

const emit = defineEmits([
  'update:modelValue',
  'dropdown-visible-change',
  'search',
  'change',
  'search-more'
])

const value2 = computed({
  get() {
    const modelValue = props.modelValue || []

    return modelValue.map(item => {
      return {
        value: item.id,
        label: item.display_name
      }
    })
  },
  set(val) {
    const val2 = val.map(item => {
      const { value, label } = item
      const label2 = label.trim()
      return {
        id: value,
        display_name: label2
      }
    })

    emit('update:modelValue', val2)
  }
})

const selectOptions = computed(() => {
  return props.options.slice(0, value2.value.length + 7).map(item => {
    return { value: item[0], label: item[1] }
  })
})

async function handleSearch(val) {
  emit('search', val)
}

function dropdownVisibleChange(open) {
  if (open) {
    emit('dropdown-visible-change')
  }
}

function handleChange(val) {
  const val2 = val.map(item => {
    const { value, label } = item
    const label2 = label.trim()
    return {
      id: value,
      display_name: label2
    }
  })

  emit('change', val2)
}

function searchMore() {
  emit('search-more')
}
</script>

<style scoped></style>
